package fcf.cat;


import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import fcf.cat.Config;

public class Utils {
	
	static List<String> RESULT_FINAL = new ArrayList<String>(); //variable donde guardamos los logs que enviaremos por email

	/**
	 * Comprueba si existe fichero 
	 * @param fichero
	 * @return
	 * @throws IOException
	 */
	public static boolean existeFichero(String fichero) throws IOException{
	      
	      Path archivo = Paths.get(Config.CSV_FOLDER+fichero);
	      
	      boolean fileExists = Files.exists(archivo, LinkOption.NOFOLLOW_LINKS);
	      
	      if(fileExists == true){
	    	  System.out.println("***** Fichero "+fichero+" existe");
	    	  
	    	  Path fichero_backup = Paths.get(Config.CSV_FOLDER+fichero+"_backup_"+getFecha());
	    	  
			  Files.copy(archivo, fichero_backup);
			  System.out.println("***** Backup "+fichero+" creado");

	      }
	      return fileExists;
	}
	
	/**
	 * 
	 * @param fichero
	 */
	public static void eliminarFichero(String fichero){
		
		Path archivo = Paths.get(Config.CSV_FOLDER+fichero);
		
		try {
		    Files.delete(archivo);
		    System.out.println("***** Fichero "+fichero+" eliminado");
		} catch (NoSuchFileException x) {
		    System.err.format("%s: no such" + " file or directory%n", archivo);
		} catch (DirectoryNotEmptyException x) {
		    System.err.format("%s not empty%n", archivo);
		} catch (IOException x) {
		    // File permission problems are caught here.
		    System.err.println(x);
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public static String getFecha(){
		Calendar now = Calendar.getInstance();
	  	int year = now.get(Calendar.YEAR);
	  	int month = now.get(Calendar.MONTH+1);
	  	int day = now.get(Calendar.DAY_OF_MONTH);
	  	int hour = now.get(Calendar.HOUR_OF_DAY);
	  	int minute = now.get(Calendar.MINUTE);
	  	int seconds = now.get(Calendar.SECOND);
	    String fecha = day+"-"+month+"-"+year+"_"+hour+"."+minute+"."+seconds;
	    return fecha;
	}
	
	
public static String validarString(String aux){
			
		aux = aux.toLowerCase(); //string en minusculas
		aux = stripAccents(aux);//quita acentos
		aux = aux.trim();//elimina espacios en blanco
		//aux = comprobarPrimerCaracter(aux);
		aux = eliminarValor(": ","-",aux);	
		aux = eliminarValor(":","-",aux);
		aux = eliminarValor(" ","-",aux);
		aux = eliminarValor("'","-",aux);
		aux = eliminarValor("´","",aux);
		aux = eliminarValor("`","-",aux);
		aux = eliminarValor("’","-",aux);
		aux = eliminarValor(",","",aux);
		aux = eliminarValor("!","",aux);
		aux = eliminarValor("\n","null",aux);
		aux = eliminarValor("¡","",aux);
		aux = eliminarValor("?","",aux);
		aux = eliminarValor("¿","",aux);
		aux = eliminarValor("(","",aux);
		aux = eliminarValor(")","",aux);
		aux = eliminarValor(".","",aux);
		aux = eliminarValor("/","-",aux);
		aux = eliminarValor("ª","",aux);
		aux = eliminarValor("ª","",aux);
		aux = eliminarValor("•",".",aux);
		aux = eliminarValor("·",".",aux);
		aux = eliminarValor("--","-",aux);
		aux = eliminarValor("--","-",aux);
		aux = eliminarValor("\"","",aux);
		aux = eliminarValor("---","-",aux);
		//aux = eliminarValor("","",aux);
		aux = eliminarUltimoCaracter(aux);
		return aux;
	}
	
	/**
	 * 
	 * @String val - Caracteres que queremos substituir
	 * @String subs - Valor con el que substituimos la cadena val
	 * @String aux - String completo donde estan los valores a substituir
	 * @return
	 */
	public static String eliminarValor(String val,String subs,String aux){
		return aux.replace(val,subs);
	}
	
	public static String stripAccents(String val){
		return StringUtils.stripAccents(val);
	}

	
	public static String comprobarPrimerCaracter(String val){
		String primerChar = String.valueOf(val.charAt(0));
		
		if(primerChar.equals("-")){
			return val.substring(1);
		}

		if(primerChar.equals("\"")){
			return val.substring(1);
		}

		return val;
	}
	
	public static String htmlEntities(String aux){
		String[] htmlentities = new String[65];
		 
		htmlentities[0] = "";
		htmlentities[1] = "";
		htmlentities[2] = "";
		htmlentities[3] = "À.&Agrave;";
		htmlentities[4] = "Á.&Aacute;";
		htmlentities[5] = "Â.&Acirc;";
		htmlentities[6] = "Ã.&Atilde;";
		htmlentities[7] = "Ä.&Auml;";
		htmlentities[8] = "Å.&Aring;";
		htmlentities[9] = "Æ.&AElig;";
		htmlentities[10] = "Ç.&Ccedil;";
		htmlentities[11] = "È.&Egrave;";
		htmlentities[12] = "É.&Eacute;";
		htmlentities[13] = "Ê.&Ecirc;";
		htmlentities[14] = "Ë.&Euml;";
		htmlentities[15] = "Ì.&Igrave;";
		htmlentities[16] = "Í.&Iacute;";
		htmlentities[17] = "Î.&Icirc;";
		htmlentities[18] = "Ï.&Iuml;";
		htmlentities[19] = "Ð.&ETH;";
		htmlentities[20] = "Ñ.&Ntilde;";
		htmlentities[21] = "Ò.&Ograve;";
		htmlentities[22] = "Ó.&Oacute;";
		htmlentities[23] = "Ô.&Ocirc;";
		htmlentities[24] = "Õ.&Otilde;";
		htmlentities[25] = "Ö.&Ouml;";
		htmlentities[26] = "Ø.&Oslash;";
		htmlentities[27] = "Ù.&Ugrave;";
		htmlentities[28] = "Ú.&Uacute;";
		htmlentities[29] = "Û.&Ucirc;";
		htmlentities[30] = "Ü.&Uuml;";
		htmlentities[31] = "Ý.&Yacute;";
		htmlentities[32] = "Þ.&THORN;";
		htmlentities[33] = "ß.&szlig;";
		htmlentities[34] = "à.&agrave;";
		htmlentities[35] = "á.&aacute;";
		htmlentities[36] = "â.&acirc;";
		htmlentities[37] = "ã.&atilde;";
		htmlentities[38] = "ä.&auml;";
		htmlentities[39] = "å.&aring;";
		htmlentities[40] = "æ.&aelig;";
		htmlentities[41] = "ç.&ccedil;";
		htmlentities[42] = "è.&egrave;";
		htmlentities[43] = "é.&eacute;";
		htmlentities[44] = "ê.&ecirc;";
		htmlentities[45] = "ë.&euml;";
		htmlentities[46] = "ì.&igrave;";
		htmlentities[47] = "í.&iacute;";
		htmlentities[48] = "î.&icirc;";
		htmlentities[49] = "ï.&iuml;";
		htmlentities[50] = "ð.&eth;";
		htmlentities[51] = "ñ.&ntilde;";
		htmlentities[52] = "ò.&ograve;";
		htmlentities[53] = "ó.&oacute;";
		htmlentities[54] = "ô.&ocirc;";
		htmlentities[55] = "õ.&otilde;";
		htmlentities[56] = "ö.&ouml;";
		htmlentities[57] = "ø.&oslash;";
		htmlentities[58] = "ù.&ugrave;";
		htmlentities[59] = "ú.&uacute;";
		htmlentities[60] = "û.&ucirc;";
		htmlentities[61] = "ü.&uuml;";
		htmlentities[62] = "ý.&yacute;";
		htmlentities[63] = "þ.&thorn;";
		htmlentities[64] = "ÿ.&yuml;";
		
		for(String tt : htmlentities){
			String[] strArray = tt.split("\\.");
			String subs = "";
			String nuevo = "";
			int i = 1;
			 for (String str : strArray) {
				 if(i==1){subs = str;}
				 if(i==2){nuevo = str;}
			  i++;
			 }
			 eliminarValor(subs,nuevo,aux);
        }
				
		return aux;
	}
	
	public static String eliminarUltimoCaracter(String val){
		char ultimoChar = val.charAt(val.length() - 1);
		if(Character.isLetter(ultimoChar) || Character.isDigit(ultimoChar)){
			return val;
		}else{
			return val.substring(0,val.length()-1);
		}
	}
	
	public static void nuevaLinea(){
		System.out.println("**********************");
	}
	
	public static void linea(String texto){
		setResult(texto);
		System.out.println("***** "+texto);
	}
	
	public static void eliminarFicherosTemporales(String carpeta){
		
		try {
		  Utils.linea("Eliminando ficheros ...");
          File directory = new File(carpeta);
          FileUtils.cleanDirectory(directory);
          Utils.linea("Ficheros eliminados satisfactoriamente");
        } catch (IOException e) {
        	Utils.linea(e.getMessage());
        }
		
	}
	
	public static void setResult(String texto){

		DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  	    Calendar cal = Calendar.getInstance();
		RESULT_FINAL.add(texto+" - "+dateFormat.format(cal.getTime()));
	}
	
	public static List<String> getResult(){
		return RESULT_FINAL;
	}
	
	private static String OS = System.getProperty("os.name").toLowerCase();
	
	/**
	 * 
	 * @return
	 */
	public static boolean detectarSO(){

		linea("SISTEMA OPERATIVO => "+OS );
		
		if (isWindows()) {
			Config.CSV_FOLDER = "D:/java/tmp/";
			Config.BD_USER = "root";
			Config.BD_PASS = "corredera";
        } else if (isUnix()) {
        	Config.CSV_FOLDER = "/var/tmp/java/";
        	Config.BD_USER = "fcf";
        	Config.BD_PASS = "fcf";
        } else {
        	return false;
        }
		return true;
	}
	
	public static boolean isWindows() {
        return (OS.indexOf("win") >= 0);
    }

    public static boolean isMac() {
        return (OS.indexOf("mac") >= 0);
    }

    public static boolean isUnix() {
        return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
    }

    public static boolean isSolaris() {
        return (OS.indexOf("sunos") >= 0);
    }
    
    public static String getOS(){
        if (isWindows()) {
            return "win";
        } else if (isMac()) {
            return "osx";
        } else if (isUnix()) {
            return "uni";
        } else if (isSolaris()) {
            return "sol";
        } else {
            return "err";
        }
    }
    
    
	
}
